package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.pipeline.Filter;
import com.example.universitylibraryback.pipeline.ReaderRegistrationContext;
import java.util.concurrent.BlockingQueue;

/**
 * 读者信息验证过滤器
 * 负责验证读者信息的有效性
 */
public class DataValidationFilter implements Filter<ReaderRegistrationContext>, Runnable {
    private BlockingQueue<ReaderRegistrationContext> inputQueue;
    private BlockingQueue<ReaderRegistrationContext> outputQueue;

    @Override
    public void process(BlockingQueue<ReaderRegistrationContext> inputQueue,
                        BlockingQueue<ReaderRegistrationContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                ReaderRegistrationContext context = inputQueue.take();
                if (!context.isValid()) {
                    outputQueue.put(context); // 如果无效，直接传递到下一环节
                    continue;
                }
                // 简单的验证逻辑
                if (context.getReaderId() == null || !context.getReaderId().matches("R\\d+")) {
                    context.setValid(false);
                    context.setMessage("Error: Reader ID must start with 'R' followed by digits.");
                } else if (context.getReaderName() == null || context.getReaderName().isEmpty()) {
                    context.setValid(false);
                    context.setMessage("Error: Reader name cannot be empty.");
                } else if (context.getEmail() == null || !context.getEmail().contains("@")) {
                    context.setValid(false);
                    context.setMessage("Error: Invalid email format.");
                } else {
                    context.setMessage("Data validation passed.");
                }
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("DataValidationFilter interrupted.");
        }
    }
}